import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../common.dart';

class Market extends StatefulWidget {
  Market({super.key});

  @override
  State<Market> createState() => _SettingPageState();
}

RxInt cid = (-1).obs;

final RxInt _index = 0.obs;

getGoods() {
  getData(
    url: '/market/goods',
    data: {
      'page': "1",
      'per_page': "999",
      'categorie_id': '${cid.value}',
      'key': _controller.text,
      'is_box': '${_index.value}',
    },
  ).then((res) {
    if (res != null) {
      list.value = res['list'];
    }
  });
}

RxList list = [].obs;
late TextEditingController _controller;
final FocusNode _focusNode = FocusNode();

void _handleSearch() {
  getGoods();
  _focusNode.unfocus(); // 收起键盘
}

class _SettingPageState extends State<Market> {
  RxInt index = (-1).obs;
  RxList twoList = [].obs;
  RxInt tindex = 0.obs;
  RxList categories = [].obs;

  getCategories() {
    getData(url: '/market/categories').then((res) {
      if (res != null) {
        categories.value = res;
        getGoods();
      }
    });
  }

  @override
  void initState() {
    super.initState();
    _controller = TextEditingController();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      getCategories();
    });
  }

  @override
  void dispose() {
    super.dispose();
    _controller.dispose();
  }

  @override
  Widget build(BuildContext context) {
    con(context);
    // final totalHeight = MediaQuery.of(context).padding.top;
    final screenWidth = MediaQuery.of(context).size.width;
    final screenheight = MediaQuery.of(context).size.height - 230;
    final spacing = 12.0; // 间距
    final itemWidth = (screenWidth - spacing) / 2;
    const itemHeight = 250.0; // 固定高度
    return Scaffold(
      body: Stack(
        children: [
          ListView(
            children: [
              // SizedBox(height: 15),
              // Container(
              //   height: 30,
              //   margin: EdgeInsets.symmetric(horizontal: 30),
              //   decoration: BoxDecoration(
              //     borderRadius: BorderRadius.circular(5),
              //     color: Color(0XFFF8F9FD),
              //   ),
              //   child: Row(
              //     mainAxisAlignment: MainAxisAlignment.center,
              //     children: [
              //       Expanded(
              //         child: Obx(
              //           () => Container(
              //             alignment: Alignment.center,
              //             decoration: BoxDecoration(
              //               borderRadius: BorderRadius.circular(10),
              //               color:
              //                   _index.value == 0
              //                       ? Color(0XFF0F172B)
              //                       : Color(0XFFF8F9FD),
              //             ),
              //             child: GestureDetector(
              //               onTap: () {
              //                 _index.value = 0;
              //                 cid.value = -1;
              //                 index.value = -1;
              //                 getGoods();
              //               },
              //               child: Text(
              //                 '数字藏品',
              //                 style: TextStyle(
              //                   fontSize: 15,
              //                   color:
              //                       _index.value == 0
              //                           ? Color(0XFFffffff)
              //                           : Color(0XFF0F172B),
              //                 ),
              //               ),
              //             ),
              //           ),
              //         ),
              //       ),
              //       Expanded(
              //         child: Obx(
              //           () => Container(
              //             alignment: Alignment.center,
              //             decoration: BoxDecoration(
              //               borderRadius: BorderRadius.circular(10),
              //               color:
              //                   _index.value == 1
              //                       ? Color(0XFF0F172B)
              //                       : Color(0XFFF8F9FD),
              //             ),
              //             child: GestureDetector(
              //               onTap: () {
              //                 _index.value = 1;
              //                 cid.value = 0;
              //                 getGoods();
              //               },
              //               child: Text(
              //                 '数字盲盒',
              //                 style: TextStyle(
              //                   fontSize: 15,
              //                   color:
              //                       _index.value == 1
              //                           ? Color(0XFFffffff)
              //                           : Color(0XFF0F172B),
              //                 ),
              //               ),
              //             ),
              //           ),
              //         ),
              //       ),
              //     ],
              //   ),
              // ),
              SizedBox(height: 20),
              SearchBar(),
              Obx(() => SizedBox(height: _index.value == 1 ? 0 : 20)),

              Obx(
                () =>
                    _index.value == 1
                        ? SizedBox()
                        : SizedBox(
                          height: 30,
                          child: ListView(
                            scrollDirection: Axis.horizontal,
                            children: [
                              GestureDetector(
                                onTap: () {
                                  index.value = -1;
                                  cid.value = -1;

                                  getGoods();
                                },
                                child: Container(
                                  margin: EdgeInsets.only(left: 15),
                                  alignment: Alignment.center,
                                  padding: EdgeInsets.symmetric(horizontal: 15),
                                  decoration: BoxDecoration(
                                    color:
                                        index.value == -1
                                            ? Color(0XFF0F172B)
                                            : Color(0XFFF8F9FD),
                                    borderRadius: BorderRadius.circular(30),
                                  ),
                                  child: Text(
                                    '推荐',
                                    style: TextStyle(
                                      fontSize: 14,
                                      color:
                                          index.value == -1
                                              ? Color(0XFFffffff)
                                              : Color(0XFF0F172B),
                                    ),
                                  ),
                                ),
                              ),
                              GestureDetector(
                                onTap: () {
                                  index.value = -2;
                                  cid.value = -2;
                                  getGoods();
                                },
                                child: Container(
                                  margin: EdgeInsets.only(left: 15),
                                  alignment: Alignment.center,
                                  padding: EdgeInsets.symmetric(horizontal: 15),
                                  decoration: BoxDecoration(
                                    color:
                                        index.value == -2
                                            ? Color(0XFF0F172B)
                                            : Color(0XFFF8F9FD),
                                    borderRadius: BorderRadius.circular(30),
                                  ),
                                  child: Text(
                                    '收藏',
                                    style: TextStyle(
                                      fontSize: 14,
                                      color:
                                          index.value == -2
                                              ? Color(0XFFffffff)
                                              : Color(0XFF0F172B),
                                    ),
                                  ),
                                ),
                              ),

                              for (var item in categories.asMap().entries)
                                GestureDetector(
                                  onTap: () {
                                    index.value = item.key;
                                    cid.value = item.value['id'];
                                    twoList.value = item.value['sub'];
                                    getGoods();
                                  },
                                  child: Container(
                                    margin: EdgeInsets.only(left: 15),
                                    alignment: Alignment.center,
                                    padding: EdgeInsets.symmetric(
                                      horizontal: 15,
                                    ),
                                    decoration: BoxDecoration(
                                      color:
                                          item.key == index.value
                                              ? Color(0XFF0F172B)
                                              : Color(0XFFF8F9FD),
                                      borderRadius: BorderRadius.circular(30),
                                    ),
                                    child: Text(
                                      '${item.value['title']}',
                                      style: TextStyle(
                                        fontSize: 14,
                                        color:
                                            item.key == index.value
                                                ? Color(0XFFffffff)
                                                : Color(0XFF0F172B),
                                      ),
                                    ),
                                  ),
                                ),
                            ],
                          ),
                        ),
              ),

              SizedBox(height: 20),
              Obx(
                () =>
                    _index.value == 0 && index.value == -1 ||
                            _index.value == 0 && index.value == -2 ||
                            _index.value == 1
                        ? lise(spacing, itemWidth, itemHeight + 10)
                        : //..推荐
                        Container(
                          constraints: BoxConstraints(
                            minHeight: screenheight, // 最小高度
                          ),
                          color: Color(0XFFF8F9FD),
                          child: Row(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Column(
                                children: [
                                  for (var item in twoList.asMap().entries)
                                    GestureDetector(
                                      onTap: () {
                                        tindex.value = item.key;
                                        cid.value = item.value['id'];
                                        getGoods();
                                      },
                                      child: Container(
                                        width: 80,
                                        height: 40,
                                        decoration: BoxDecoration(
                                          borderRadius: BorderRadius.only(
                                            topRight: Radius.circular(15),
                                          ),
                                          color:
                                              item.key == tindex.value
                                                  ? Color(0XFF0F172B)
                                                  : Color(0XFFF8F9FD),
                                        ),
                                        alignment: Alignment.center,
                                        child: Text(
                                          '${item.value['title']}',
                                          style: TextStyle(
                                            fontSize: 12,
                                            color:
                                                item.key == tindex.value
                                                    ? Color(0XFFFFFFFF)
                                                    : Color(0XFF0F172B),
                                          ),
                                        ),
                                      ),
                                    ),
                                ],
                              ),
                              Expanded(
                                child: lises(
                                  spacing,
                                  itemWidth,
                                  250,
                                  screenheight,
                                ),
                              ),
                            ],
                          ),
                        ),
              ),
            ],
          ),
          // Positioned(
          //   right: 0,
          //     bottom: 30,
          //     child: GestureDetector(
          //       onTap: (){
          //         toNamed('/market/snap_up');
          //       },
          //       child: wImage(url: 'qianggou',width: 80),
          //     )

          //   ),
        ],
      ),
    );
  }
}

Widget lises(spacing, itemWidth, itemHeight, screenheight) {
  return Container(
    constraints: BoxConstraints(
      minHeight: screenheight, // 最小高度
    ),
    color: Color(0XFFFFFFFF),
    padding: EdgeInsets.symmetric(horizontal: 15),
    child: Obx(
      () =>
          list.isNotEmpty
              ? GridView.count(
                crossAxisCount: 2,
                crossAxisSpacing: spacing,
                mainAxisSpacing: spacing,
                childAspectRatio: itemWidth / itemHeight,
                shrinkWrap: true,
                physics: NeverScrollableScrollPhysics(),
                children: List.generate(list.length, (index) {
                  return GestureDetector(
                    onTap: () {
                      toNamed(
                        '/web_tabs/market/market_list?id=${list[index]['id']}',
                      );
                    },
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Stack(
                          children: [
                            ClipRRect(
                              borderRadius: BorderRadius.only(
                                topLeft: Radius.circular(15),
                                topRight: Radius.circular(15),
                              ),
                              child: Image.network(
                                '${list[index]['thumb']}',
                                height: itemWidth - 60,
                                fit: BoxFit.fill,
                              ),
                            ),
                            if (list[index]['on_sell'] == 0)
                              Positioned(
                                child: Container(
                                  height: itemWidth - 60,
                                  color: Color(0X88000000),
                                  child: Image.asset(
                                    'static/web/tuisahi.png',
                                    fit: BoxFit.fitWidth,
                                  ),
                                ),
                              ),
                            // Positioned(
                            //   top: 10,
                            //   right: 10,
                            //   child: Image.asset(
                            //     'static/web/haixin.png',
                            //     width: 25,
                            //     fit: BoxFit.fitWidth,
                            //   ),
                            // ),
                          ],
                        ),
                        SizedBox(height: 5),
                        Text(
                          '${list[index]['title']}',
                          style: TextStyle(
                            fontSize: 14,
                            color: Color(0XFF0F172B),
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.end,
                          children: [
                            Text(
                              '￥',
                              style: TextStyle(
                                fontSize: 11,
                                color: Color(0XFF0F172B),
                              ),
                            ),
                            list[index]['on_sell'] != 0
                                ? Text(
                                  '${list[index]['min_price'] / 100}',
                                  style: TextStyle(
                                    fontSize: 16,
                                    color: Color(0XFF0F172B),
                                    fontWeight: FontWeight.bold,
                                  ),
                                )
                                : Text(
                                  '--',
                                  style: TextStyle(
                                    fontSize: 16,
                                    color: Color(0XFF0F172B),
                                  ),
                                ),
                            SizedBox(width: 5),
                            Text(
                              '起',
                              style: TextStyle(
                                fontSize: 11,
                                color: Color(0XFF999999),
                              ),
                            ),
                          ],
                        ),
                      ],
                    ),
                  );
                }),
              )
              : isdata(),
    ),
  );
}

Widget lise(spacing, itemWidth, itemHeight) {
  return Padding(
    padding: EdgeInsets.symmetric(horizontal: 15),
    child: Obx(
      () =>
          list.isNotEmpty
              ? GridView.count(
                crossAxisCount: 2,
                crossAxisSpacing: spacing,
                mainAxisSpacing: spacing,
                childAspectRatio: itemWidth / itemHeight,
                shrinkWrap: true,
                physics: NeverScrollableScrollPhysics(),
                children: List.generate(list.length, (index) {
                  return GestureDetector(
                    onTap: () {
                      toNamed(
                        '/web_tabs/market/market_list?id=${list[index]['id']}',
                      );
                    },
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Stack(
                          children: [
                            ClipRRect(
                              borderRadius: BorderRadius.circular(10),
                              child: Image.network(
                                '${list[index]['thumb']}',
                                width: 167,
                                height: 167,
                                fit: BoxFit.fill,
                              ),
                            ),
                            if (list[index]['on_sell'] == 0)
                              Positioned(
                                child: Container(
                                  decoration: BoxDecoration(
                                    color: Color(0X88000000),
                                    borderRadius: BorderRadius.circular(10),
                                  ),
                                  width: 167,
                                  height: 167,
                                  child: Image.asset(
                                    'static/web/tuisahi.png',
                                    fit: BoxFit.fitWidth,
                                  ),
                                ),
                              ),
                            //  Positioned(
                            //   top: 10,
                            //   right: 10,
                            //   child:
                            //   Image.asset(
                            //     'static/web/baxiin.png',
                            //     width: 25,
                            //     fit: BoxFit.fitWidth,
                            //   )
                            //   ,
                            // ),
                          ],
                        ),
                        SizedBox(height: 5),
                        Text(
                          '${list[index]['title']}',
                          style: TextStyle(
                            fontSize: 14,
                            color: Color(0XFF0F172B),
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.end,
                          children: [
                            Text(
                              '￥',
                              style: TextStyle(
                                fontSize: 11,
                                color: Color(0XFF0F172B),
                              ),
                            ),
                            list[index]['on_sell'] != 0
                                ? Text(
                                  '${list[index]['min_price'] / 100}',
                                  style: TextStyle(
                                    fontSize: 16,
                                    color: Color(0XFF0F172B),
                                    fontWeight: FontWeight.bold,
                                  ),
                                )
                                : Text(
                                  '--',
                                  style: TextStyle(
                                    fontSize: 16,
                                    color: Color(0XFF0F172B),
                                  ),
                                ),
                            SizedBox(width: 5),
                            Text(
                              '起',
                              style: TextStyle(
                                fontSize: 11,
                                color: Color(0XFF999999),
                              ),
                            ),
                          ],
                        ),
                      ],
                    ),
                  );
                }),
              )
              : isdata(),
    ),
  );
}

class SearchBar extends StatelessWidget {
  SearchBar({super.key});

  @override
  Widget build(BuildContext context) {
    return Container(
      width: 375.0,
      margin: EdgeInsets.only(left: 15, right: 15),
      height: 40.0, // 固定总高度为40dp
      decoration: BoxDecoration(
        color: Color(0xffF8F9FD),
        borderRadius: BorderRadius.circular(20.0), // 圆角调整为高度的一半
      ),
      child: Padding(
        padding: EdgeInsets.symmetric(horizontal: 16.0), // 左右内边距
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.center, // 垂直居中
          children: [
            Icon(
              Icons.search,
              color: Color(0XFF0F172B),
              size: 20.0, // 缩小图标尺寸
            ),
            SizedBox(width: 8.0),
            Expanded(
              child: TextField(
                controller: _controller,
                focusNode: _focusNode,
                onSubmitted: (value) => _handleSearch(),
                textInputAction: TextInputAction.search,
                decoration: InputDecoration(
                  hintText: '请输入藏品名称',
                  hintStyle: TextStyle(color: Color(0xff999999), fontSize: 14),
                  border: InputBorder.none,
                  isDense: true, // 关键！减少TextField默认高度
                  contentPadding: EdgeInsets.zero, // 移除内边距
                ),
                style: TextStyle(fontSize: 14.0), // 统一字体大小
              ),
            ),
          ],
        ),
      ),
    );
  }
}
